package server

import (
	"encoding/json"
	"io"
	"log"
	"net/http"
	"strconv"
	"xin-job/client/executor"
	"xin-job/client/sconf"
	"xin-job/core/biz"
)

var instance = &EmbedServer{}

func GetInstance() *EmbedServer {
	return instance
}

type EmbedServer struct {
	Server http.Server
}

// 处理每个 http 请求
func indexFunc(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	if r.Method != "POST" {
		GetInstance().err(w)
	}

	// TODO token

	switch r.URL.Path {
	case "/run":
		GetInstance().run(w, r)
	case "/beat":

	default:
		GetInstance().err(w)
	}
}

func (s *EmbedServer) Start() {
	// 读取配置文件
	err := sconf.ServerConf.Read()
	if err != nil {
		panic(err)
	}

	port := strconv.Itoa(sconf.ServerConf.Port)

	s.Server = http.Server{Addr: ":" + port}
	http.HandleFunc("/", indexFunc)

	go func() {
		err := s.Server.ListenAndServe()
		if err != nil {
			log.Printf("http server start failed, err %v\n", err)
		}
	}()
}
func (s *EmbedServer) run(w http.ResponseWriter, r *http.Request) {
	body, err := io.ReadAll(r.Body)
	if err != nil {
		http.Error(w, "Error reading request body", http.StatusInternalServerError)
		return
	}
	defer r.Body.Close()

	p := biz.TriggerParam{}
	err = json.Unmarshal(body, &p)
	if err != nil {
		http.Error(w, "Error parsing JSON", http.StatusBadRequest)
		return
	}

	// 执行 handler
	executor.GetExecutorBizImpl().Run(&p)

	data, err := json.Marshal(biz.Return[string]{
		Code: 200,
		Msg:  "success",
	})
	if err != nil {
		log.Printf("trigger err %v\n", err)
		return
	}

	w.Write(data)
}
func (s *EmbedServer) err(w http.ResponseWriter) {
	res := biz.Return[string]{Code: 500, Msg: "invalid request, HttpMethod not support."}
	resData, err := json.Marshal(res)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	w.Write(resData)
}
